package com.sheng.leetcode.year2024.interview;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author by ls
 * @date 2024/3/5
 * <p>
 * 编写一个 java 函数，实现获取 1000 个用户昵称的能力，具体要求如下：<p>
 * 1）提供一个函数 Service.get(List<Long> userIds)，支持传入 1000 个用户 ID，返回用 户 ID 及其对应的昵称<p>
 * 2）在 Service.get 内部，通过调用 UserService.getUserMap(List<Long> userIds)获取  数据，<p>
 * 但 UserService.getUserMap 每次最多只接收 50 个用户 ID，且该接口一次请求耗时 100ms<p>
 * 3）Service.get(List<Long> userIds)函数需要将所有 1000 个传入的用户 ID 一次返回， 并且耗时需要保证在 200ms 以内。<p>
 */
public class Service {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ArrayList<Long> longs = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            longs.add((long) i);
        }
        Map<Long, String> longStringMap = new Service().get(longs);
        System.out.println(longStringMap);
    }

    public Map<Long, String> get(List<Long> userIds) throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        // 将集合按照最大 50 个来进行划分
        int size = 50;
        UserService userService = new UserService();
        Map<Long, String> map = new HashMap<>();
        ExecutorService executor = Executors.newFixedThreadPool(userIds.size() / size + 1);
        for (int i = 0; i < userIds.size(); i += size) {
            List<Long> longs = userIds.subList(i, Math.min(i + size, userIds.size()));
            System.out.println(longs);
            executor.submit(() -> {
                try {
                    Map<Long, String> userMap = userService.getUserMap(longs);
                    map.putAll(userMap);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
        }
        executor.shutdown();
        long end = System.currentTimeMillis();
        System.out.println(end - start);
        return map;
    }
}

class UserService {
    public Map<Long, String> getUserMap(List<Long> userIds) throws InterruptedException {
//        if (userIds == null || userIds.size() > 50) {
//            throw new RuntimeException("userids more than 50");
//        }
//        Map<Long, String> result = new HashMap<>();
//        for (Long userId : userIds) {
//            result.put(userId, "test");
//        }
//        return result;
        Thread.sleep(100);
        return new HashMap<>();
    }
}

